package com.yimi.yinhepda.views.main.home_module.presenter;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.pda.uce.commom.util.DisplayUtil;
import com.pda.uce.commom.util.DividerDecoration;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.callbacks.UICallBack;
import com.pda.ym.entity.bean.CarPlanTaskEntity;
import com.pda.ym.entity.bean.LoadBillTaskEntity;
import com.pda.ym.entity.bean.VehTaskNodeEntity;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.SharedPreferUtil;
import com.uce.pda.module.ConnectionResultLister;
import com.uce.pda.util.ArrayUtils;
import com.uce.pda.util.JavaUtils;
import com.uce.pda.util.Utils;
import com.uce.pda.view.StickyScrollView;
import com.webview.MainHandler;
import com.webview.PadLogUtils;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.entity.bean.CheckBoxItemEntity;
import com.yimi.yinhepda.entity.request.DeleteTaskRequest;
import com.yimi.yinhepda.entity.response.CarPlanTaskResponse;
import com.yimi.yinhepda.entity.response.DeleteTaskResponse;
import com.yimi.yinhepda.utils.Common;
import com.yimi.yinhepda.utils.ToastUtil;
import com.yimi.yinhepda.views.load_module.LoadUnloadGroupActivity;
import com.yimi.yinhepda.views.load_module.LoadUtil;
import com.yimi.yinhepda.views.main.NewMainActivity;
import com.yimi.yinhepda.views.main.home_module.PeizaiDanBean;
import com.yimi.yinhepda.views.main.home_module.request.QueryAllocateTaskRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class LoadTaskPresenter {

    List<CarPlanTaskEntity> unloadTaskTableList = new ArrayList<>();

    BaseQuickAdapter<CarPlanTaskEntity, BaseViewHolder> adapter;

    RecyclerView taskRecycleView;

    NewMainActivity activity;

    StickyScrollView stickyScrollView;

    int pageSize=0;

    List<List<CarPlanTaskEntity>> carPlanTaskEnties=new ArrayList<>();

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void initView(View view, Activity paramsActivity) {
        activity = (NewMainActivity) paramsActivity;
        stickyScrollView=view.findViewById(R.id.stick_scrollview);
        taskRecycleView = view.findViewById(R.id.recycler);
        taskRecycleView.setLayoutManager(new LinearLayoutManager(activity));
        taskRecycleView.addItemDecoration(new DividerDecoration("#e5e5e5",
                DisplayUtil.dip2px(0.3f), 40, 60));
        taskRecycleView.setNestedScrollingEnabled(false);


        stickyScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY > oldScrollY) {
                    // 向下滑动
                }

                if (scrollY < oldScrollY) {
                    // 向上滑动
                }

                if (scrollY == 0) {
                    // 顶部
                }

                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    // 底部
                    if (!ArrayUtils.isEmpty(carPlanTaskEnties)){
                        pageSize++;
                        if (pageSize<carPlanTaskEnties.size()){
                            unloadTaskTableList.addAll(carPlanTaskEnties.get(pageSize));
                            if (adapter!=null){
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }
                }
            }
        });



        adapter = new BaseQuickAdapter<CarPlanTaskEntity, BaseViewHolder>(R.layout.kuaiyun_item_job_info, unloadTaskTableList) {
            @Override
            protected void convert(BaseViewHolder helper, final CarPlanTaskEntity item, int postion) {
                helper.setText(R.id.text, item.getTaskNo());
                if (item.getOperTypeCode() == 2) {
                    helper.setText(R.id.text_task_type, "卸车");
                } else {
                    helper.setText(R.id.text_task_type, "装车");
                }
                helper.setVisible(R.id.text_task_type, true);
                helper.convertView.findViewById(R.id.execute).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PadLogUtils.getInstance().loge("operTYpe" + item.getOperTypeCode());
                        if (item.getBeTask() == 1) { //车线
                            fareTask(item);
                        } else {
                            int deptType = SharedPreferUtil.getInstance().getIntValue(Common.DEPT_TYPE);
                            final List<CarPlanTaskEntity> carPlanTaskEntityList = new ArrayList<>();
                            carPlanTaskEntityList.add(item);
                            if (item.getMergeCarPlanTaskEntyList() != null) {
                                carPlanTaskEntityList.addAll(item.getMergeCarPlanTaskEntyList());
                            }
                            if (deptType == 5 || deptType == 6) {
                                LoadUtil.toNextActivity(mContext, item.getTask(), carPlanTaskEntityList, item.getOperTypeCode());
                            } else {
                                if (item.getOperTypeCode() == 2) { //卸车
                                    LoadUtil.addLoaderEmpCodes(carPlanTaskEntityList, new UICallBack() {
                                        @Override
                                        public void onError(String msg) {
                                            ToastUtil.showToast(msg);
                                        }

                                        @Override
                                        public void onSuccess(Object obj) {
                                            //获取发车计划下一站.显示，选择下一站，创建装车任务
                                            getCarPlanTaskNextDept(carPlanTaskEntityList);

                                            //显示下一站对话框
                                            LoadUtil.showNextDeptDialog(activity, carPlanTaskEntityList, item.getOperTypeCode());
                                        }
                                    });
                                } else {
                                    //获取发车计划下一站.显示，选择下一站，创建装车任务
                                    LoadUtil.showNextDeptDialog(mContext, carPlanTaskEntityList, 1);
                                }

                            }
                        }

                    }
                });

                helper.convertView.findViewById(R.id.main).setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        MyDialog.showAlertDialog(mContext, "确认删除?", "是", "否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                List<String> stowages=new ArrayList<>();
                                if (!ArrayUtils.isEmpty(item.getLoadTasks())){
                                     for (int i=0;i<item.getLoadTasks().size();i++){
                                         stowages.add(item.getLoadTasks().get(i).getStowageNo());
                                     }
                                    deleteTask(item.getOperTypeCode(), stowages, new ConnectionResultLister() {
                                        @Override
                                        public void getResult(int errorCode, Object o) {
                                            if (errorCode==0){
                                                unloadTaskTableList.remove(item);
                                                adapter.notifyDataSetChanged();
                                            }
                                        }
                                    });
                                }
                                else{
                                    ToastUtil.showToast("配载单号为空");
                                }

                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        return false;
                    }
                });


                SpannableString spannableString;
                ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.card_code_text_color));
                if (!TextUtils.isEmpty(item.getVehLineName())) {
                    if (!TextUtils.isEmpty(item.getShift())) {
                        String groupName = item.getVehLineName() + "【" + item.getVehNo() + "】   ";
                        spannableString = new SpannableString(groupName + String.format("%s班次", LoadUtil.getShift(item.getShift())));
                        spannableString.setSpan(colorSpan, item.getVehLineName().length(), groupName.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    } else {
                        if (!TextUtils.isEmpty(item.getVehNo())) {
                            spannableString = new SpannableString(item.getVehLineName() + "【" + item.getVehNo() + "】");
                            spannableString.setSpan(colorSpan, item.getVehLineName().length(), spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                        } else {
                            spannableString = new SpannableString(item.getVehLineName());
                        }
                    }
                    helper.setText(R.id.text2, spannableString);
                }
                if (!TextUtils.isEmpty(item.getPlanStartTime())) {
                    helper.setText(R.id.time, "计划发车" + item.getPlanStartTime());
                }
            }
        };
        taskRecycleView.setAdapter(adapter);
    }


    public void clearData() {
        pageSize=0;
        if (!ArrayUtils.isEmpty(carPlanTaskEnties)){
            carPlanTaskEnties.clear();
        }
        if (!ArrayUtils.isEmpty(unloadTaskTableList)) {
            unloadTaskTableList.clear();
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }


    public void getCreatedTask(final int operType, final List<UnloadTaskTable> unLoadTaskTableList, final ConnectionResultLister connectionResultLister) {
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(CarPlanTaskResponse.class)
                .setUrl(Constants.URL_V2_QUERY_LOAD_OR_UNLOAD_TASK)
                .setRequestObject(new QueryAllocateTaskRequest(SharedPreferUtil.getInstance().getValue(Common.USER_CODE), operType, SharedPreferUtil.getInstance().getDeptCode()))
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        activity.showToast(msg);
                        if (connectionResultLister != null) {
                            connectionResultLister.getResult(0, null);
                        }
                    }

                    @Override
                    public void onSuccess(Object obj) {
                       final CarPlanTaskResponse response = (CarPlanTaskResponse) obj;
                        if (response.getData() != null) {
                            Utils.getThreadPool().execute(new Runnable() {
                                @Override
                                public void run() {
                                   final List<CarPlanTaskEntity> records = getListTaskNo(operType, unLoadTaskTableList, response.getData());
                                    setOperType(operType, records);
                                    if (!ArrayUtils.isEmpty(records)&&records.size()>100){
                                        List<List<CarPlanTaskEntity>> listCarPlanTaskEnties=JavaUtils.subWithLen(records,50);
                                        carPlanTaskEnties.addAll(listCarPlanTaskEnties);
                                        MainHandler.getInstance().post(new Runnable() {
                                            @Override
                                            public void run() {
                                                unloadTaskTableList.addAll(carPlanTaskEnties.get(0));
                                                if (adapter != null) {
                                                    adapter.notifyDataSetChanged();
                                                }
                                            }
                                        });
                                    }
                                    else{
                                        MainHandler.getInstance().post(new Runnable() {
                                            @Override
                                            public void run() {
                                                unloadTaskTableList.addAll(records);
                                                if (adapter != null) {
                                                    adapter.notifyDataSetChanged();
                                                }
                                            }
                                        });
                                    }

                                }
                            });


                        }
                        if (connectionResultLister != null) {
                            connectionResultLister.getResult(0, null);
                        }
                    }
                });
    }


    UnloadTaskTableDao mUnloadTaskTableDaoObj = new UnloadTaskTableDao();
    public void deleteTask(final int operType, final List<String> stowageNos, final ConnectionResultLister connectionResultLister) {
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(DeleteTaskResponse.class)
                .setUrl(Constants.URL_DELETE_EMPCODE)
                .setRequestObject(new DeleteTaskRequest(stowageNos,operType,SharedPreferUtil.getInstance().getValue(Common.USER_CODE)))
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        activity.showToast(msg);
                        if (connectionResultLister != null) {
                            connectionResultLister.getResult(-1, null);
                        }
                    }

                    @Override
                    public void onSuccess(Object obj) {
                       final DeleteTaskResponse response = (DeleteTaskResponse) obj;
                        if (response.isSuccess()) {
                            try{
                                Utils.getThreadPool().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        for (int i=0;i<stowageNos.size();i++){
                                            mUnloadTaskTableDaoObj.deleteByTaskNo(stowageNos.get(i));
                                        }
                                    }
                                });
                            }catch (Exception e){

                            }
                            if (connectionResultLister != null) {
                                connectionResultLister.getResult(0, null);
                            }
                        }
                        else{
                            ToastUtil.showToast(response.getErrorMessages());
                            if (connectionResultLister != null) {
                                connectionResultLister.getResult(-1, null);
                            }
                        }

                    }
                });
    }


    private void setOperType(int type, List<CarPlanTaskEntity> records) {
        if (!ArrayUtils.isEmpty(records)) {
            for (int i = 0; i < records.size(); i++) {
                records.get(i).setOperTypeCode(type);
            }
        }
    }


    /*****
     *
     * @param unLoadTaskTableList 根据登录人查询未完成的任务
     * @param records 服务器返回的未完成的任务
     * @return
     */
    private List<CarPlanTaskEntity> getListTaskNo(int operType, List<UnloadTaskTable> unLoadTaskTableList, List<CarPlanTaskEntity> records) {
        if (!ArrayUtils.isEmpty(unLoadTaskTableList)) {
            //将本地缓存的合并任务的配载单号进行拼接
            HashMap<String, StringBuilder> map = new HashMap<>();
            for (int i = 0; i < unLoadTaskTableList.size(); i++) {
                StringBuilder stringBuilderPeiZaiDan = map.get(unLoadTaskTableList.get(i).getTask());
                if (stringBuilderPeiZaiDan == null) {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(unLoadTaskTableList.get(i).getStowageNo() + ",");
                    map.put(unLoadTaskTableList.get(i).getTask(), stringBuilder);

                } else {
                    stringBuilderPeiZaiDan.append(unLoadTaskTableList.get(i).getStowageNo() + ",");
                    map.put(unLoadTaskTableList.get(i).getTask(), stringBuilderPeiZaiDan);
                }
            }
            //取出合并任务的配载单号
            List<PeizaiDanBean> peizaiDanList = new ArrayList<>();
            Iterator iter = map.entrySet().iterator();
            PeizaiDanBean peizaiDanBean;
            while (iter.hasNext()) {
                peizaiDanBean = new PeizaiDanBean();
                Map.Entry<String, StringBuilder> entry = (Map.Entry) iter.next();
                StringBuilder value = entry.getValue();
                if (!TextUtils.isEmpty(value)) {
                    peizaiDanBean.peizaiDan = value.substring(0, (value.length() - 1));
                    peizaiDanBean.task = entry.getKey();
                    peizaiDanList.add(peizaiDanBean);
                }

            }

            //更改服务器配载单号
            if (!ArrayUtils.isEmpty(records)) {
                for (int j = 0; j < records.size(); j++) {
                    records.get(j).setOperTypeCode(operType);
                    for (int d = 0; d < peizaiDanList.size(); d++)
                        if (records.get(j).getBeTask() == 0) {
                            if (peizaiDanList.get(d).peizaiDan.contains(records.get(j).getTaskNo())) {
                                records.get(j).setTaskNo(peizaiDanList.get(d).peizaiDan);
                                records.get(j).setTask(peizaiDanList.get(d).task);
                            }
                        }
                }
            }
            //删除重复的配载单号
            removeDuplicate(records);
        }
        return records;
    }


    public static void removeDuplicate(List<CarPlanTaskEntity> list) {
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(j).getTaskNo().equals(list.get(i).getTaskNo())) {
                    if (list.get(i).getMergeCarPlanTaskEntyList() == null) {
                        List<CarPlanTaskEntity> carPlanTaskEntityList = new ArrayList<>();
                        carPlanTaskEntityList.add(list.get(j));
                        list.get(i).setMergeCarPlanTaskEntyList(carPlanTaskEntityList);
                    } else {
                        list.get(i).getMergeCarPlanTaskEntyList().add(list.get(i));
                    }
                    list.remove(j);
                }
            }
        }
    }


    private void fareTask(CarPlanTaskEntity carPlanTaskEntity) {
        int deptType = SharedPreferUtil.getInstance().getIntValue(Common.DEPT_TYPE);
        List<CarPlanTaskEntity> carPlanTaskEntityList = new ArrayList<CarPlanTaskEntity>();
        carPlanTaskEntityList.add(carPlanTaskEntity);
        if (deptType == 5 || deptType == 6) {
            //判断是否是分拨,跳转至装卸组
            LoadUtil.toClassActivity(activity, carPlanTaskEntityList.get(0).getTask(), carPlanTaskEntityList, LoadUnloadGroupActivity.class, carPlanTaskEntity.getOperTypeCode());
        } else {
            //获取发车计划下一站.显示，选择下一站，创建装车任务
            getCarPlanTaskNextDept(carPlanTaskEntityList);

            //显示下一站对话框
            LoadUtil.showNextDeptDialog(activity, carPlanTaskEntityList, carPlanTaskEntity.getOperTypeCode());
        }
    }

    /**
     * 下一站待选择集合
     */
    private List<CheckBoxItemEntity> mNextDeptList = new ArrayList<>();
    /**
     * 已选择的下一站集合
     */
    private List<CheckBoxItemEntity> mSelectedNextDeptList = new ArrayList<>();

    /**
     * 获取发车计划下一站
     */
    private void getCarPlanTaskNextDept(List<CarPlanTaskEntity> tasks) {
        mNextDeptList.clear();
        for (CarPlanTaskEntity planTask : tasks) {
            for (VehTaskNodeEntity node : planTask.getNodes()) {
                CheckBoxItemEntity checkBoxItemEntity = new CheckBoxItemEntity();
                if(planTask.getLoadTasks() != null){
                    for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                        if (node.getTaskNodeCode().equals(loadTask.getDestDeptCode())) {
                            checkBoxItemEntity.setCheck(true);
                            checkBoxItemEntity.setTempCheck(true);
                        }
                    }
                }
                checkBoxItemEntity.setName(node.getTaskNodeName());
                checkBoxItemEntity.setCode(node.getTaskNodeCode());
                checkBoxItemEntity.setNodeNum(node.getNodeNum());
                mNextDeptList.add(checkBoxItemEntity);
            }
        }
    }

    //删除任务
    public void removeTask(List<String> stringList) {
        //正确 可删除多个
        Iterator<CarPlanTaskEntity> iterator = unloadTaskTableList.iterator();
        while (iterator.hasNext()) {
            CarPlanTaskEntity carPlanTaskEntity = iterator.next();
            for (int i = 0; i < stringList.size(); i++) {
                if (!TextUtils.isEmpty(carPlanTaskEntity.getTaskNo()) &&carPlanTaskEntity.getTaskNo().equals(stringList.get(i))) {
                    iterator.remove();//使用迭代器的删除方法删除
                }
            }
        }
        adapter.notifyDataSetChanged();
    }

}